package com.oauth.global.client.ui;

import java.util.List;
import java.util.Map;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.oauth.components.client.rpc.OAuthAsnyCallBack;
import com.oauth.components.client.ui.HasWidgetInfo;
import com.oauth.global.client.beans.ApplicationClientBean;
import com.oauth.global.client.rpc.GlobalRemoteServiceAsync;

public class BrowseWindow extends Composite {

	private static BrowseWindowUiBinder uiBinder = GWT.create(BrowseWindowUiBinder.class);

	interface BrowseWindowUiBinder extends UiBinder<Widget, BrowseWindow> {
	}

	Map<Long, HasWidgetInfo> widgetMap;

	@UiField
	VerticalPanel vPanel;

	public BrowseWindow() {
		initWidget(uiBinder.createAndBindUi(this));
	}

	private GlobalRemoteServiceAsync globalService;

	public Grid addBrowseWidget(List<ApplicationClientBean> pResult) {

		Grid grid = new Grid(4, 2);
		int row = 0, column = 0;
		for (ApplicationClientBean clientBean : pResult) {
			grid.setWidget(row, column, getApplicationPanel(clientBean));
			grid.getCellFormatter().setWidth(row, column, "2px");
			row = column == 1 ? ++row : row;
			column = column == 0 ? 1 : 0;

		}

		if (pResult.isEmpty()) {
			grid.setWidget(
					row,
					column,
					new HTML(
							"<div align=center><b>There are no applications to add.</b><br/> Many new applications will be added shortly.</div>"));
		}

		/*
		 * NOTE: Add code here to show subscribed applications with remove
		 * button.
		 */
		return grid;
	}

	private Widget getApplicationPanel(ApplicationClientBean pClientBean) {
		ApplicationPanel appPanel = new ApplicationPanel();
		HasWidgetInfo HasWidgetInfo = widgetMap.get(pClientBean.getId());
		appPanel.setApplicationBean(pClientBean, HasWidgetInfo.getWidgetImage());
		appPanel.setService(globalService);
		return appPanel;
	}

	public void setService(GlobalRemoteServiceAsync globalRemoteServiceAsync) {
		globalService = globalRemoteServiceAsync;
	}

	public void setMaps(Map<Long, HasWidgetInfo> widgetMap) {
		this.widgetMap = widgetMap;
	}

	public void initBrowseWidget() {
		vPanel.clear();
		globalService.getUnSubscribedApplications(

		new OAuthAsnyCallBack<List<ApplicationClientBean>>() {
			public void onSuccess(List<ApplicationClientBean> result) {
				vPanel.add(addBrowseWidget(result));
			}
		});
	}

}